package com.salton123.imagepicker.custom

import android.app.Activity
import android.content.Context
import android.content.Intent
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentActivity
import com.salton123.imagepicker.ImagePicker
import com.salton123.imagepicker.bean.ImageItem
import com.salton123.imagepicker.log.ILog
import com.salton123.imagepicker.ui.ImageGridActivity
import com.salton123.imagepicker.ui.ImagePickerFragment
import com.salton123.imagepicker.ui.ImagePickerFragment2
import com.salton123.imagepicker.ui.ImagePreviewDelActivity
import com.salton123.imagepicker.util.IImageLoader
import com.salton123.imagepicker.util.Utils
import com.salton123.imagepicker.view.CropImageView
import java.util.*


object ImagePickerUtil {
    private const val TAG = "ImagePickerUtil"
    const val REQUEST_CODE_PICK = 100
    const val REQUEST_CODE_TAKE = 101
    const val REQUEST_CODE_PREVIEW = 102


    //初始化这次使用的ImagePicker
    fun initDefaultPicker(
        crop: Boolean,    //是否裁剪
        selectLimit: Int, //选择数量限制
        multi: Boolean  //是否多选
    ): ImagePicker {
        return ImagePicker.getInstance().apply {
            this.isShowCamera = true  //显示拍照按钮
            this.isCrop = crop        //允许裁剪（单选才有效）
            this.isSaveRectangle = true //是否按矩形区域保存
            this.isMultiMode = multi
            this.selectLimit = selectLimit    //选中数量限制
            this.style = CropImageView.Style.RECTANGLE  //裁剪框的形状
            this.focusWidth = 1000   //裁剪框的宽度。单位像素（圆形自动取宽高最小值）
            this.focusHeight = 1000  //裁剪框的高度。单位像素（圆形自动取宽高最小值）
            //配置默认值,一次性用的
            this.setCropPixelLimitIntercept(0, null)
            this.setSelectSizeLimitIntercept(0, Int.MAX_VALUE, null)
            this.setVideoSelectSizeLimitIntercept(Long.MAX_VALUE, null)
            this.setSelectAmountLimitIntercept(null)
            this.clickPreviewListener = null
            this.setCropTextGuide("", "#999999")
            this.isFilterGif = true
            this.isRotateSwitch = false
            this.isFilterVideo = true
            this.completeText = ""
        }
    }

    //自定义loader，避免图库版本太低无法加载图片，内部使用Glide 4.9.0
    fun initCustomImageLoader(iImageLoader: IImageLoader?): ImagePicker {
        return ImagePicker.getInstance().apply {
            this.imageLoader = iImageLoader
        }
    }

    //获取ImagePicker实例，在app启动初始化通用配置，例如权限提示，拍照按钮颜色等。
    fun getImagePicker(): ImagePicker = ImagePicker.getInstance()


    //初始化必要的按钮多语言
    fun initImagePickerConstanceString(
        cancel: String = "",
        choose: String = "",
        allPictures: String = "",
        complete: String = "",
        preview: String = "",
        takePhoto: String = "",
        hasChoose: String = "",
        sdCardPermissionToast: String = "",
        cameraPermissionToast: String = ""
    ) {
        ImagePickerTextRepository.cancel = cancel
        ImagePickerTextRepository.choose = choose
        ImagePickerTextRepository.allPictures = allPictures
        ImagePickerTextRepository.complete = complete
        ImagePickerTextRepository.preview = preview
        ImagePickerTextRepository.takePhoto = takePhoto
        ImagePickerTextRepository.hasChoose = hasChoose
        ImagePickerTextRepository.sdCardPermissionToast = sdCardPermissionToast
        ImagePickerTextRepository.cameraPermissionToast = cameraPermissionToast
    }

    //在相册里选择
    fun pickPhoto(context: Context, selectList: ArrayList<ImageItem>) {
        val intent = Intent(context, ImageGridActivity::class.java)
        intent.putExtra(ImageGridActivity.EXTRAS_IMAGES, selectList)
        when (context) {
            is FragmentActivity -> context.startActivityForResult(intent, REQUEST_CODE_PICK)
            is Fragment -> context.startActivityForResult(intent, REQUEST_CODE_PICK)
            else -> ILog.e(TAG, "pickPhoto fail")
        }
    }

    //在相册里选择,采用直接回调
    fun pickPhoto(
        activity: Activity,
        selectList: ArrayList<ImageItem>,
        callback: CallBackRepository.IImagePickerCallback
    ) {
        try {
            if (activity is FragmentActivity) {
                val fm = activity.supportFragmentManager
                val transaction = fm.beginTransaction()
                val imagePickerFragment = fm.findFragmentByTag(ImagePickerFragment.TAG)
                imagePickerFragment?.let {
                    transaction.remove(it)
                }
                val fragment = ImagePickerFragment().apply {
                    this.imagePickerCallback = callback
                    this.requestCode = REQUEST_CODE_PICK
                    this.selectList = selectList
                }
                transaction.add(fragment, ImagePickerFragment.TAG).commitAllowingStateLoss()
                fm.executePendingTransactions()
            } else {
                val fm = activity.fragmentManager
                val transaction = fm?.beginTransaction()
                val imagePickerFragment = fm?.findFragmentByTag(ImagePickerFragment2.TAG)
                imagePickerFragment?.let {
                    transaction?.remove(it)
                }
                val fragment = ImagePickerFragment2().apply {
                    this.imagePickerCallback = callback
                    this.requestCode = REQUEST_CODE_PICK
                    this.selectList = selectList
                }
                transaction?.add(fragment, ImagePickerFragment2.TAG)?.commitAllowingStateLoss()
                fm?.executePendingTransactions()
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    //拍照
    fun takePhoto(context: Context, selectList: ArrayList<ImageItem>) {
        val intent = Intent(context, ImageGridActivity::class.java)
        intent.putExtra(ImageGridActivity.EXTRAS_TAKE_PICKERS, true) // 是否是直接打开相机
        intent.putExtra(ImageGridActivity.EXTRAS_IMAGES, selectList)
        when (context) {
            is FragmentActivity -> context.startActivityForResult(intent, REQUEST_CODE_TAKE)
            is Fragment -> context.startActivityForResult(intent, REQUEST_CODE_TAKE)
            else -> ILog.e(TAG, "takePhoto fail")
        }
    }


    //拍照,采用直接回调
    fun takePhoto(
        activity: Activity,
        selectList: ArrayList<ImageItem>,
        callback: CallBackRepository.IImagePickerCallback
    ) {
        try {
            if (activity is FragmentActivity) {
                val fm = activity.supportFragmentManager
                val transaction = fm.beginTransaction()
                val imagePickerFragment = fm.findFragmentByTag(ImagePickerFragment.TAG)
                imagePickerFragment?.let {
                    transaction.remove(it)
                }
                val fragment = ImagePickerFragment().apply {
                    this.imagePickerCallback = callback
                    this.requestCode = REQUEST_CODE_TAKE
                    this.selectList = selectList
                }
                transaction.add(fragment, ImagePickerFragment.TAG).commitAllowingStateLoss()
                fm.executePendingTransactions()
            } else {
                val fm = activity.fragmentManager
                val transaction = fm?.beginTransaction()
                val imagePickerFragment = fm?.findFragmentByTag(ImagePickerFragment2.TAG)
                imagePickerFragment?.let {
                    transaction?.remove(it)
                }
                val fragment = ImagePickerFragment2().apply {
                    this.imagePickerCallback = callback
                    this.requestCode = REQUEST_CODE_TAKE
                    this.selectList = selectList
                }
                transaction?.add(fragment, ImagePickerFragment2.TAG)?.commitAllowingStateLoss()
                fm?.executePendingTransactions()
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    //预览,position < 已选相片的边界值
    fun previewPhoto(context: Context, selectList: ArrayList<ImageItem>, position: Int) {
        if (!selectList.isNullOrEmpty() && position < selectList.size) {
            val intent = Intent(context, ImagePreviewDelActivity::class.java)
            intent.putExtra(ImagePicker.EXTRA_IMAGE_ITEMS, selectList)
            intent.putExtra(ImagePicker.EXTRA_SELECTED_IMAGE_POSITION, position)
            intent.putExtra(ImagePicker.EXTRA_FROM_ITEMS, true)
            when (context) {
                is FragmentActivity -> context.startActivityForResult(intent, REQUEST_CODE_PREVIEW)
                is Fragment -> context.startActivityForResult(intent, REQUEST_CODE_PREVIEW)
                else -> ILog.e(TAG, "previewPhoto fail")
            }
        }
    }


    //预览,position < 已选相片的边界值,采用直接回调
    fun previewPhoto(
        activity: Activity,
        selectList: ArrayList<ImageItem>,
        position: Int,
        callback: CallBackRepository.IImagePickerCallback
    ) {
        if (!selectList.isNullOrEmpty() && position < selectList.size) {
            try {
                if (activity is FragmentActivity) {
                    val fm = activity.supportFragmentManager
                    val transaction = fm.beginTransaction()
                    val imagePickerFragment = fm.findFragmentByTag(ImagePickerFragment.TAG)
                    imagePickerFragment?.let {
                        transaction.remove(it)
                    }
                    val fragment = ImagePickerFragment().apply {
                        this.imagePickerCallback = callback
                        this.requestCode = REQUEST_CODE_PREVIEW
                        this.selectList = selectList
                        this.previewPosition = position
                    }
                    transaction.add(fragment, ImagePickerFragment.TAG).commitAllowingStateLoss()
                    fm.executePendingTransactions()
                } else {
                    val fm = activity.fragmentManager
                    val transaction = fm?.beginTransaction()
                    val imagePickerFragment = fm?.findFragmentByTag(ImagePickerFragment2.TAG)
                    imagePickerFragment?.let {
                        transaction?.remove(it)
                    }
                    val fragment = ImagePickerFragment2().apply {
                        this.imagePickerCallback = callback
                        this.requestCode = REQUEST_CODE_PREVIEW
                        this.selectList = selectList
                        this.previewPosition = position
                    }
                    transaction?.add(fragment, ImagePickerFragment2.TAG)?.commitAllowingStateLoss()
                    fm?.executePendingTransactions()
                }
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }
    }

    //解析onActivityResult返回的数据
    fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?): ArrayList<ImageItem>? {
        var list: ArrayList<ImageItem>? = null
        if (resultCode == ImagePicker.RESULT_CODE_ITEMS) {
            //添加图片返回
            if (data != null && (requestCode == REQUEST_CODE_PICK || requestCode == REQUEST_CODE_TAKE)) {
                list =
                    data.getSerializableExtra(ImagePicker.EXTRA_RESULT_ITEMS) as? ArrayList<ImageItem>
            }
        } else if (resultCode == ImagePicker.RESULT_CODE_BACK) {
            //预览图片返回
            if (data != null && requestCode == REQUEST_CODE_PREVIEW) {
                list =
                    data.getSerializableExtra(ImagePicker.EXTRA_IMAGE_ITEMS) as? ArrayList<ImageItem>
            }
        }
        Utils.removeDuplicate(list) //去重
        return list
    }
}